<?php
namespace app\api\controller;
use think\Db;
use think\Controller;

require_once "wxBizDataCrypt.php";
class Phone extends Controller
{
  public function AjaxReturn($code,$msg,$data=array())
  {

    $returnData=array(
      "code"=>$code
    );
    if($msg){
      $returnData["message"]=$msg;
    }
    if(!empty($data))
    {
      $returnData["data"]=$data;
    }
    exit(json_encode($returnData));
  }
  
  public function init()
  {
    $openid = input('openid');
    $uid=db('user')->where('code',$openid)->value('uid');
    $code = input('code');
    $appid="wx6c1a86ee3e43e4a3";
    $secret="32f54b415ab46d898b2714c327b8d4b9";
    $iv = input('iv');
    $encryptedData = input('encryptedData');
    $url='https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
    $apiData=file_get_contents($url);

    $session_key =  json_decode($apiData)->session_key;

    $openid =  json_decode($apiData)->openid;

    $pc = new WXBizDataCrypt($appid, $session_key);

    $errCode = $pc->decryptData($encryptedData, $iv, $data);
    $data=json_decode($data);
    $phone = $data->phoneNumber;
    if($errCode == 0){

      $time=date('Y-m-d H:i:s');
      $add=db('user')->where('uid',$uid)->update(['phone'=>$phone,'createtime'=>$time,'nickname'=>'无名','head_portrait'=>'https://www.agrimanu.cn/upload/linshiimg/20190411095739.jpg']);
      //添加公司表、实名认证表、粉丝表
      //防止重复提交提前判断是否创建成功！
      $com=db('company')->where('uid',$uid)->find();
      if(!$com)
      {
        $company=db('company')->insert(['uid'=>$uid]);
      }
      $rea=db('real')->where('uid',$uid)->find();
      if(!$rea)
      {
        $real=db('real')->insert(['uid'=>$uid]);
      }
      $fan=db('fans')->where('uid',$uid)->find();
      if(!$fan)
      {
        $fans=db('fans')->insert(['uid'=>$uid,'createtime'=>$time]);
      }
      //默认关注官方账号
      $gflg=db('user')->where('gflg',1)->select();
      $a=array();
      foreach ($gflg as $key=>$value)
      {
        $a[]=$value['uid'];
      }
      //官方账号字符串
      $time=date('Y-m-d H:i:s');
      if($a==array())
      {
        $str='';
      }
      else
      {
        foreach ($a as $fuid)
        {
          //让所有官方账号添加我为粉丝
          $chuan=db('fans')->where('uid',$fuid)->field('fuid')->find();
          $str2=$chuan['fuid'].$uid.',';
          $update2=db('fans')->where('uid',$fuid)->update(['fuid'=>$str2]);
          //我关注官方账号
          $acc=db('fans')->where('uid',$uid)->field('guid')->find();
          $str3=$acc['guid'].$fuid.',';
          $up=db('fans')->where('uid',$uid)->field('guid')->update(['guid'=>$str3]);
        }
        //关注官方账号生成日志
        foreach ($a as $value2)
        {
          $ribiao=db('ribiao')->insert(['uid'=>$uid,'bid'=>$value2,'createtime'=>$time,'zhaungtai'=>1]);
        }
      }

      $this->AjaxReturn('1','授权手机号成功',$phone);
    }else{
      $this->AjaxReturn('-1','授权手机号失败',$errCode);
    }
  }

}